<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>心形动画</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        heart: '#ff3e6c',
                        background: '#fff5f7',
                    },
                    fontFamily: {
                        sans: ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .heart-beat {
                animation: heartbeat 1.5s ease-in-out infinite;
            }
            @keyframes heartbeat {
                0% { transform: scale(1); }
                14% { transform: scale(1.1); }
                28% { transform: scale(1); }
                42% { transform: scale(1.1); }
                70% { transform: scale(1); }
            }
        }

        /* Safari特定样式修复 */
        @supports (-webkit-overflow-scrolling: touch) {
            input[type="range"] {
                -webkit-appearance: none;
                height: 2px;
                background: #e5e7eb;
                border-radius: 1px;
            }
            input[type="range"]::-webkit-slider-thumb {
                -webkit-appearance: none;
                width: 18px;
                height: 18px;
                border-radius: 50%;
                background: #ff3e6c;
                cursor: pointer;
                border: none;
            }
            button {
                -webkit-tap-highlight-color: transparent;
            }
        }
    </style>
</head>
<body class="bg-background min-h-screen flex flex-col items-center justify-center p-4 font-sans">
    <div class="relative bg-white rounded-xl shadow-xl p-4 md:p-6 transition-all duration-300 hover:shadow-2xl w-full max-w-md">
        <!-- 控制面板 -->
        <div class="flex flex-wrap justify-center gap-4 mb-4">
            <div class="flex items-center gap-2">
                <label for="size" class="text-gray-700 font-medium">大小:</label>
                <input type="range" id="size" min="50" max="300" value="200"
                       class="w-32 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-heart">
                <span id="sizeValue" class="text-gray-700 font-medium">200</span>
            </div>

            <div class="flex items-center gap-2">
                <label for="color" class="text-gray-700 font-medium">颜色:</label>
                <input type="color" id="color" value="#ff3e6c" class="w-8 h-8 p-0 border-0 cursor-pointer">
            </div>

            <button id="animateBtn" class="bg-heart hover:bg-heart/90 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center gap-1">
                <i class="fa fa-pause"></i>
                <span>暂停</span>
            </button>
        </div>

        <!-- Canvas容器 -->
        <div class="flex justify-center items-center">
            <canvas id="heartCanvas" class="max-w-full h-auto"></canvas>
        </div>
    </div>

    <footer class="mt-8 text-center text-gray-500 text-sm px-4">
        <p>使用 Canvas 绘制 | 拖动滑块调整大小，点击按钮控制动画</p>
    </footer>

    <script>
        // 兼容性处理：检测并替换Safari不支持的方法
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = (function() {
                return window.webkitRequestAnimationFrame ||
                       function(callback) {
                           return setTimeout(callback, 16);
                       };
            })();
        }

        if (!window.cancelAnimationFrame) {
            window.cancelAnimationFrame = (function() {
                return window.webkitCancelAnimationFrame ||
                       window.webkitCancelRequestAnimationFrame ||
                       function(id) {
                           clearTimeout(id);
                       };
            })();
        }

        // 获取Canvas元素和上下文
        const canvas = document.getElementById('heartCanvas');
        const ctx = canvas.getContext('2d');

        // 获取控制元素
        const sizeSlider = document.getElementById('size');
        const sizeValue = document.getElementById('sizeValue');
        const colorPicker = document.getElementById('color');
        const animateBtn = document.getElementById('animateBtn');

        // 心形绘制参数
        let size = parseInt(sizeSlider.value);
        let color = colorPicker.value;
        let isAnimating = true;
        let animationId = null;
        let animationTime = 0;

        // 设置Canvas尺寸
        function setCanvasSize() {
            // 为了确保绘制清晰，考虑设备像素比
            const dpr = window.devicePixelRatio || 1;
            const windowWidth = window.innerWidth;
            const canvasSize = Math.min(windowWidth - 40, 500); // 适应移动设备

            canvas.width = canvasSize * dpr;
            canvas.height = canvasSize * dpr;
            canvas.style.width = `${canvasSize}px`;
            canvas.style.height = `${canvasSize}px`;

            // 缩放上下文以匹配高DPI屏幕
            ctx.scale(dpr, dpr);

            // 重新绘制心形
            drawHeart();
        }

        // 绘制心形函数
        function drawHeart(currentSize = size) {
            // 清除Canvas
            const canvasWidth = canvas.width / (window.devicePixelRatio || 1);
            const canvasHeight = canvas.height / (window.devicePixelRatio || 1);
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);

            // 获取中心位置
            const centerX = canvasWidth / 2;
            const centerY = canvasHeight / 2 + currentSize * 0.1;

            // 开始绘制路径
            ctx.beginPath();

            // 使用参数方程绘制心形 - 兼容所有浏览器
            for (let t = 0; t <= 2 * Math.PI; t += 0.01) {
                const sinT = Math.sin(t);
                const x = 16 * sinT * sinT * sinT; // 替换pow方法，提高兼容性
                const cosT = Math.cos(t);
                const y = 13 * cosT - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t);

                // 缩放并定位到中心
                const pointX = centerX + x * (currentSize / 16);
                const pointY = centerY - y * (currentSize / 16); // 减号是因为Canvas的Y轴向下

                // 如果是第一个点，移动到该点，否则绘制线
                if (t === 0) {
                    ctx.moveTo(pointX, pointY);
                } else {
                    ctx.lineTo(pointX, pointY);
                }
            }

            // 闭合路径
            ctx.closePath();

            // 设置填充样式和填充
            ctx.fillStyle = color;
            ctx.fill();

            // 添加描边
            ctx.strokeStyle = '#d12853';
            ctx.lineWidth = 2;
            ctx.stroke();
        }

        // 动画函数
        function animate() {
            if (!isAnimating) return;

            // 计算当前大小，使用正弦函数创建脉动效果
            animationTime += 0.05;
            const pulse = 1 + 0.1 * Math.sin(animationTime);
            const currentSize = size * pulse;

            // 绘制心形
            drawHeart(currentSize);

            // 继续动画
            animationId = requestAnimationFrame(animate);
        }

        // 事件监听器 - 为移动设备优化触摸体验
        sizeSlider.addEventListener('input', () => {
            size = parseInt(sizeSlider.value);
            sizeValue.textContent = size;
            drawHeart();
        });

        colorPicker.addEventListener('input', () => {
            color = colorPicker.value;
            drawHeart();
        });

        animateBtn.addEventListener('click', () => {
            isAnimating = !isAnimating;

            if (isAnimating) {
                animateBtn.innerHTML = '<i class="fa fa-pause"></i><span>暂停</span>';
                animate();
            } else {
                animateBtn.innerHTML = '<i class="fa fa-play"></i><span>动画</span>';
                if (animationId) {
                    cancelAnimationFrame(animationId);
                }
                drawHeart(); // 恢复到原始大小
            }
        });

        // 窗口大小改变时重新设置Canvas
        window.addEventListener('resize', setCanvasSize);

        // 处理iOS Safari的视口变化
        window.addEventListener('orientationchange', setCanvasSize);

        // 初始化
        setCanvasSize();
        animate();
    </script>
</body>
</html>